<template>
  <div>
    <div>【关键词条】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud'

const props = defineProps({
  data: {
    type: Object,
    required: true,
  }
})

// 1. 初始化 echarts 实例
let mChart = null
const target = ref(null)

onMounted(() => {
  mChart = echarts.init(target.value)
  renderChart()
})

const randomRGB = () => {
  const r = Math.floor(Math.random() * 255)
  const g = Math.floor(Math.random() * 255)
  const b = Math.floor(Math.random() * 255)
  return `rgb(${r},${g},${b})`
}

// 2. 构建 option 配置对象 
const renderChart = () => {
  var options;
    if (props.data == null || props.data.length == 0) {  //暂无数据
        options = {
            title: {
                text: '暂无数据',
                x: 'center',
                y: 'center',
                textStyle: {
                  fontSize: 14,
                  fontWeight: 'normal',
                }
              }
              
        }
    } else {
    options = {
      title:{
          text:''
        },
      // tooltip 配置
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: '搜索次数: {c}', // 显示关键词和对应的 value 值 {b}: {c}
        position: function (pos, params, dom, rect, size) {
          // 鼠标右上角显示
          return [pos[0] + 10, pos[1] - 10];
        },
        backgroundColor: 'white', // 白色背景
        textStyle: {
          color: '#333333', // 深灰色文字
          fontSize: 14
        },
        padding: 10,
        borderWidth: 1,
        borderColor: '#cccccc',
        borderRadius: 4
      },
      // 核心配置 
      series: [
        {
          type: 'wordCloud',
          sizeRange: [20, 86],
          rotationRange: [0, 0],
          gridSize: 0,
          layoutAnimation: true,
          textStyle: {
            color: randomRGB
          },
          data: props.data,
          emphasis: {
            textStyle: {
              fontWeight: 'bold',
              color: '#000'
            }
          }
        }
      ]
    }
  }
  // 3. 通过 实例.setOptions(option)
  mChart.setOption(options,true);
}

watch(() => props.data, renderChart)
</script>

<style lang="scss" scoped>
</style>